local filename = "getverificationcode.lua"

local timetool = require "timetool"
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog =require "filelog"
local base = require "base"

local redisdao = require "redisdao"
local json = require "cjson.safe"
json.encode_sparse_array(true, 1, 1)

require "pubenum"

local service = nil
local CMD = {
	service = nil
}

--验证码过期时长,默认10min后过期
local verif_code_expiratetime = 600

--验证码可重新获取的间隔时间,默认60s
local verif_code_refresh_time = 60

--
--生成一个6位随机验证码
--
local function gen_verification_code()
    local code = ""
    local len = 6
    for i = 1,len  do
        code = code .. base.get_random(1,9)
    end
    
    return code
end

--
--处理获取验证码请求
--必要参数 phonenum手机号
--
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end

    --验证参数合法性
    if type(msgbody.phonenum) ~= "string" or string.len(msgbody.phonenum) ~= 11 then
        return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "错误的手机号码"}
    end

    local phonenum = msgbody.phonenum
    local first = tonumber(string.sub(phonenum,1,1))
    local high = tonumber(string.sub(phonenum,1,5))
    local low = tonumber(string.sub(phonenum,6,11))

    if first ~= 1 or not high or not low then
        return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "错误的手机号码"}
    end

    --当前验证码不为空，表示已获取过,检验是否可以重新获得
    if service.cur_verif_code and service.cur_verif_phonenum == phonenum then
        local cur_time = timetool.get_time()
        local last_get_time = service.cur_verif_code_expiratetime - verif_code_expiratetime
        local dur_time = cur_time - last_get_time
        if dur_time <= verif_code_refresh_time then
            return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "操作过于频繁，请稍后重试！"}
        end
    end
	
    --当前认证手机号
    service.cur_verif_phonenum = phonenum
    --当前验证码
    service.cur_verif_code = gen_verification_code()
    --验证码过期时间
    service.cur_verif_code_expiratetime = timetool.get_time() + verif_code_expiratetime

    --通知平台服发送验证码
    skynet.send(".mainnode", "lua", "cmd", "notice_platform_server", rid, phonenum, service.cur_verif_code)

    --保存验证码
    local key = rid or service.rid
    local variable = {
        cur_verif_phonenum = service.cur_verif_phonenum,
        cur_verif_code = service.cur_verif_code,
        cur_verif_code_expiratetime = service.cur_verif_code_expiratetime,
    }
    if key then
        redisdao.query_data(".gmmqredis", "set", key .. ":cur_verifinfo", json.encode(variable))
    end

	return { }
end

return CMD